package edu.unipd.p2t.connection;

import java.util.Vector;

import android.util.Log;
import edu.unipd.p2t.communicaton.CommunicationManager;

/**
 * Data structure that regulates discovered devices
 */
public class LeakyBucket extends Thread {

	private int maxConnections;

	private Vector<Device> deviceList = new Vector<Device>();
	
	private final String TAG = "p2t";
	
	private final long SLEEP_TIME = 500;

	public LeakyBucket( int connections ) {
		maxConnections = connections;
	}

	/**
	 * inserts a new device in the process queue
	 */
	public void add( Device dev ) {

		if( !deviceList.contains( dev ) ) {	 
			// adding the first device to the list
			deviceList.add( dev );

			// starting pool processing, if not already running
			// TODO check Thread safety with thread start/stop
			if( !isAlive() )
				start();
		}
	}

	
	@Override
	public void run() {
		
		while( !deviceList.isEmpty() ) {

			if( BtDevice.getActiveConnections() < maxConnections ) {
				// processing the first device on the list
				Device pop = deviceList.firstElement();
				deviceList.remove( 0 );

				CommunicationManager.getInstance().newConnectedDevice( pop );
			} else {
				try { sleep( SLEEP_TIME ); } catch( InterruptedException e ) {
					Log.d( TAG, "LeackyBucket.run: interrupted exception" ); }
			}
		}
	}
	
}
